<script setup lang="ts">
import { inject, onMounted, onUnmounted, ref, watchEffect } from 'vue'
import { useEventListener } from "@vueuse/core";
import { useResizeObserver } from "@vueuse/core";
import { EChart } from '@/models/reactiveComponent';
import * as cpUtils from './utils';
import Error from "./Error.vue";
import * as injectKeys from "@/services/injectKeys";

import { type TEchartUpdateInfo } from "@/models/reactiveComponent";
import { value2sqlValue } from '@/services/dbServices';

const datasetServices = inject(injectKeys.datasetKey)!
const sqlServices = inject(injectKeys.sqlAnalyzeKey)!
const dbServices = inject(injectKeys.dbKey)!
const cpServices = inject(injectKeys.componentKey)!

const props = defineProps<{ model: EChart }>()
const model = props.model

const filterUtils = cpUtils.getEChartsFilterUtils(model, {
    sqlAnalyze: sqlServices,
    dataset: datasetServices,
    db: dbServices,
})
const chartOpt = filterUtils.getData()
const chartDiv = ref(null as unknown as HTMLDivElement)


const valueMap = new Map<TEchartUpdateInfo['valueType'], string>([
    ['x', 'name'],
    ['value', 'name'],
    ['y', 'value'],
])

const hoverUpdateFilterFns = model.updateInfos.filter(v => v.actionType === 'hover').map(info => {
    return (params: echarts.ECElementEvent) => {
        const propName = valueMap.get(info.valueType)!

        return params[propName]

    }
})

const cssWidth = model.width
const cssHeight = model.height


onMounted(() => {
    const myChart = echarts.init(chartDiv.value,null,{renderer:cpServices.getApp().echartsRenderer})

    watchEffect(() => {
        myChart.setOption(chartOpt.value, true)
    })

    myChart.on('mouseover', 'series', (params) => {

        hoverUpdateFilterFns.forEach(fn => {
            const fnValue = fn(params)
            const sqlValue = value2sqlValue(fnValue)
            filterUtils.addFilter(`= ${sqlValue}`)
        })

    })

    myChart.on('mouseout', 'series', (params) => {
        filterUtils.removeFilter()
    })

    myChart.on('click', 'series', (params) => {

        // const valueMap = {
        //     x: 'name',

        // }

        // const sqlValue = dbUtils.value2sqlValue(params['name'])
        // filterUtils.addFilter(`= ${sqlValue}`)


    })

    useEventListener('resize', () => {
        myChart.resize()
    })

    useResizeObserver(chartDiv, () => {
        myChart.resize()
    })

    onUnmounted(() => {
        myChart.dispose()
    })



})


</script>

<template>
    <div class="echart-box" :data-tag="model.tag">

        <Error>
            <div class="echart" ref="chartDiv">
            </div>

        </Error>

    </div>
</template>

<style scoped>
.echart {
    min-width: 18em;
    min-height: 15em;
    width: 100%;
    height: v-bind(cssHeight);
}
</style>